package com.educatioin.manage.wechat.service;

import com.alibaba.fastjson.JSONObject;
import com.educatioin.manage.web.productorder.entity.PayResult;
import com.educatioin.manage.wechat.config.WXPayConfigImpl;
import com.educatioin.manage.wechat.dto.UnifiedOrderReq;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @create 2018-04-19 下午 7:14
 * @desc ${DESCRIPTION}
 **/
@Service
public class WeChatPayService {
    private Logger logger = LoggerFactory.getLogger(WeChatPayService.class);
    @Autowired
    private RestTemplate restTemplate;

    private WXPay wxPay = new WXPay(WXPayConfigImpl.getInstance());

    public WeChatPayService() throws Exception {
    }

    /**
     * 统一下单接口
     * @return
     */
    public Map<String,String> unifiedOrder(UnifiedOrderReq unifiedOrderReq){
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String> resp = new HashMap<String, String>();
        data.put("body", unifiedOrderReq.getBody());
        data.put("out_trade_no", unifiedOrderReq.getOutTradeNo());
        data.put("device_info", unifiedOrderReq.getDeviceInfo());
        data.put("total_fee", String.valueOf(unifiedOrderReq.getTotalFee()));
        data.put("spbill_create_ip", unifiedOrderReq.getSpbillCreateIp());
        data.put("notify_url", unifiedOrderReq.getNotifyUrl());
        data.put("trade_type", unifiedOrderReq.getTradeType());
        data.put("openid",unifiedOrderReq.getOpenid());

        try {
            logger.info("prepay request: " + data.toString());
            resp = wxPay.unifiedOrder(data);
            logger.info("prepay result: " + resp.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resp;

    }

    /**
     * 查询订单
     * @param outTradeNo
     * @return
     */
    public Map<String,String> orderQuery(String outTradeNo){
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String> resp = new HashMap<String, String>();
        data.put("out_trade_no", "outTradeNo");

        try {
            resp = wxPay.orderQuery(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    public PayResult validatePayResult (String notifyData) throws Exception{
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map
        PayResult payResult= new PayResult();
        if (wxPay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            payResult.setResultCode(notifyMap.get("return_code"));
            payResult.setAppId(notifyMap.get("appid"));
            payResult.setMchId(notifyMap.get("mch_id"));
            payResult.setResultCode(notifyMap.get("result_code"));
            payResult.setOpenid(notifyMap.get("openid"));
            payResult.setTotalFee(notifyMap.get("total_fee"));
            payResult.setSettlementTotalFee(notifyMap.get("settlement_total_fee"));
            payResult.setTransactionId(notifyMap.get("transaction_id"));
            payResult.setOutTradeNo(notifyMap.get("out_trade_no"));
            payResult.setTimeEnd(notifyMap.get("time_end"));
            logger.info("pay result:" + JSONObject.toJSONString(payResult));
        }
        else {
            payResult.setReturnCode(notifyMap.get("return_code"));
            payResult.setReturnMsg(notifyMap.get("return_msg"));
        }
        return payResult;
    }
}
